const DB = require('../lib/Sequlize')
const {
    Op
} = require('sequelize')
const md5 = require('md5')

class UserController {
    // 获取管理员列表
    async getUserList(ctx){
        const data = await DB.user.findAll()
        global.Response.success(ctx, undefined, data)
    }

    // 登录
    async login(ctx){
        const {
            account,
            password
        } = ctx.request.body

        const user = await DB.user.findOne({
            where: {
                // 可选择邮箱登录或者账号登录
                account,
                password: md5(password),
            }
        })
        if (user) {
            let lastLoginAt = await user.get('updatedAt')
            // 更新登录时间
            user.updatedAt = global.Moment().format('YYYY-MM-DD HH:mm:ss')
            await user.save()

            const data = {
                user,
                token: 'uPutToken(admin.id, admin.auth)'
            }
            global.Response.success(ctx, '登录成功', data)
        } else {
            global.Response.fail(ctx, '账号或密码错误')
        }
    }

    // 添加子管理员
    async addUser(ctx) {
        let {
            account, name, password = '123456'
        } = ctx.request.body


        const user = await DB.user.create({
            account,
            name,
            password: md5(password),// 初始密码
            createdAt: global.Moment().format('YYYY-MM-DD HH:mm:ss'),
            updatedAt: global.Moment().format('YYYY-MM-DD HH:mm:ss')
        })

        await user.save()

        const data = {
            user: {
                userId: user.id,
                account: user.account,
                name: user.name,
            },
            // token: uPutToken(user.id)
        }
        global.Response.success(ctx, '添加子管理员成功', data)
    }

    // 修改密码
    async updatePwd(ctx) {
        const {
            id,
            password,
        } = ctx.request.body

        const user = await DB.user.update({
            password: md5(password),
            updatedAt: global.Moment().format('YYYY-MM-DD HH:mm:ss')
        })

        global.Response.success(ctx, '更新成功')
    }
}

module.exports = new UserController
